﻿using System.Linq;
using System.Collections.Generic;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

namespace NFox.Cad.ExtendMethods
{

    public static class SymbolTableEx
    {

        public static ObjectId Add(this SymbolTable table, Transaction tr, SymbolTableRecord record)
        {
            ObjectId id = table.Add(record);
            tr.AddNewlyCreatedDBObject(record, true);
            return id;
        }

        public static IEnumerable<SymbolTableRecord> GetRecords(this SymbolTable table, Transaction tr, OpenMode mode, bool includingErased)
        {
            foreach (ObjectId id in table)
            {
                SymbolTableRecord record = tr.GetObject(id, mode, includingErased) as SymbolTableRecord;
                if (record != null && (includingErased || !id.IsErased))
                    yield return record;
            }
        }

        public static IEnumerable<SymbolTableRecord> GetRecords(this SymbolTable table, Transaction tr, OpenMode mode)
        {
            foreach (ObjectId id in table)
            {
                if (!id.IsErased)
                {
                    SymbolTableRecord record = tr.GetObject(id, mode, false) as SymbolTableRecord;
                    if (record != null)
                        yield return record;
                }
            }
        }

        public static IEnumerable<SymbolTableRecord> GetRecords(this SymbolTable table, Transaction tr)
        {
            return GetRecords(table, tr, OpenMode.ForRead);
        }

        /// <summary>
        /// 在符号表中获取对应键值的记录Id
        /// </summary>
        /// <param name="table">符号表</param>
        /// <param name="tr">事务</param>
        /// <param name="key">记录键值</param>
        /// <returns>对应键值的记录Id</returns>
        public static ObjectId GetRecorId(this SymbolTable table, Transaction tr, string key) 
        {

            if (table.Has(key))
            {
                if (Application.Version.Major < 18)
                {
                    ObjectId idres = table[key];
                    if (!idres.IsErased)
                        return idres;
                    return
                        table.Cast<ObjectId>()
                        .Where(id => !id.IsErased)
                        .Select(id => tr.GetObject(id, OpenMode.ForRead) as SymbolTableRecord)
                        .FirstOrDefault(str => str.Name == key)
                        .ObjectId;
                }
                else
                {
                    return table[key];
                }
            }
            return ObjectId.Null;
        }

    }
}
